package com.wwwarehouse.carddesk.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.wei.android.lib.fingerprintidentify.FingerprintIdentify;
import com.wei.android.lib.fingerprintidentify.base.BaseFingerprint;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.eventbus_event.CardDeskMessageEvent;
import com.wwwarehouse.carddesk.eventbus_event.CardDeskTaskFunctionEvent;
import com.wwwarehouse.carddesk.fragment.DeskGroupFragment;
import com.wwwarehouse.carddesk.fragment.DeskMessageFragment;
import com.wwwarehouse.carddesk.fragment.DeskMyFragment;
import com.wwwarehouse.carddesk.fragment.DeskTaskFragment;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.eventbus_event.CardDeskEvent;
import com.wwwarehouse.common.eventbus_event.CardDeskRefreshEvent;
import com.wwwarehouse.common.tools.LogUtils;

import java.util.Stack;

import de.greenrobot.event.EventBus;

public class CardDeskActivity extends BaseCardDeskActivity {
    private LinearLayout mTaskFunctionLayout;  //布局
    private TextView     mTaskTxt;   //任务
    private TextView     mFunctionTxt;  //功能

    // 点击更多出来的四个按钮和他们外面的layout
    private ImageView    mTaskbt;       // 任務
    private ImageView    mMessagebt;    // 消息
    private ImageView    mGroupbt;      // 群組
    private ImageView    mMybt;         // 我的
    private LinearLayout mTaskBtLayout; // 任务layout
    private LinearLayout mMessageBtLayout; // 消息layout
    private LinearLayout mGroupBtLayout; // 群组layout
    private LinearLayout mMyBtLayout; // 我的layout
    private RelativeLayout mMyLayout = null;

    // 四个Fragment的常量
    private String TAG_TASK    = "task";
    private String TAG_MESSAGE = "message";
    private String TAG_GROUP   = "group";
    private String TAG_MY      = "my";

    private String TAB_CURR    = null; // 当前是哪个fragment

    DeskTaskFragment      mDeskTaskFragment    = null; // 任务fragment
    DeskMessageFragment   mDeskMessageFragment = null; // 消息Fragment
    DeskGroupFragment     mDeskGroupFragment   = null; // 群组Fragment
    DeskMyFragment        mDeskMyFragment      = null; // 我的Fragment
    OnButtonClickListener onButtonClick        = null;    // 按钮点击事件

    TextView mTitleText     = null;   // 左侧title
    private Stack<Fragment> backStack = null; // Fragment栈
    PopupWindow popupWindow = null;   // 四个tab按钮的弹窗

    private ImageView mMorebt; // 更多按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView(savedInstanceState);
    }

    private void initView(Bundle savedInstanceState) {
        onButtonClick = new OnButtonClickListener();
        mMorebt = findView(R.id.more_bt);
        mTitleText = findView(R.id.title_text);
        mMorebt.setOnClickListener(onButtonClick);

        mTaskFunctionLayout = findView(R.id.ll_task_function);
        mTaskTxt = findView(R.id.tv_task);
        mFunctionTxt = findView(R.id.tv_function);

        mTaskTxt.setOnClickListener(onButtonClick);
        mFunctionTxt.setOnClickListener(onButtonClick);

        if (savedInstanceState != null) {
            // 删除内存中的fragment
            removeAllFragment();
            String tab = savedInstanceState.getString("tab");
            backStack = new Stack<>();
            if ("1".equals(tab)) {
                switchTask(TAG_TASK);
            } else if ("2".equals(tab)) {
                switchTask(TAG_MESSAGE);
            } else if ("3".equals(tab)) {
                switchTask(TAG_GROUP);
            } else if ("4".equals(tab)) {
                switchTask(TAG_MY);
            } else {
                switchTask(TAG_TASK);
            }
            savedInstanceState = null;
            recreate();
        } else {
            backStack = new Stack<>();
            switchTask(TAG_TASK);
        }
    }

    public String getTabCurr(){
        return TAB_CURR;
    }

    public void switchTaskTab() {
        mTaskTxt.setBackgroundResource(R.drawable.common_card_desk_task_check_shape);
        mTaskTxt.setTextColor(ContextCompat.getColor(mContext,R.color.common_color_c3_ffffff));

        mFunctionTxt.setBackgroundResource(R.drawable.common_card_desk_function_normal_shape);
        mFunctionTxt.setTextColor(ContextCompat.getColor(mContext,R.color.common_color_c6_585d62));

        EventBus.getDefault().post(new CardDeskTaskFunctionEvent("task_task"));
    }

    public void switchFunctionTab() {
        mFunctionTxt.setBackgroundResource(R.drawable.common_card_desk_function_check_shape);
        mFunctionTxt.setTextColor(ContextCompat.getColor(mContext,R.color.common_color_c3_ffffff));

        mTaskTxt.setBackgroundResource(R.drawable.common_card_desk_task_normal_shape);
        mTaskTxt.setTextColor(ContextCompat.getColor(mContext,R.color.common_color_c6_585d62));

        EventBus.getDefault().post(new CardDeskTaskFunctionEvent("task_function"));
    }

    class OnButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v == mTaskTxt) {
                // 任务TAB
               switchTaskTab();
            } else if (v == mFunctionTxt) {
                // 功能TAB
                switchFunctionTab();
            } else if (v == mMorebt) {
                // 显示四个tab操作按钮
                showFourTaskBt();
            } else if (v == mTaskBtLayout) {
                if (!TAB_CURR.equals(TAG_TASK)) {
                    mTaskFunctionLayout.setVisibility(View.VISIBLE);
                    mTitleText.setVisibility(View.GONE);
                    switchTask(TAG_TASK);
                }
                hideTaskBt();
            } else if (v == mMessageBtLayout) {
                if (!TAB_CURR.equals(TAG_MESSAGE)) {
                    mTaskFunctionLayout.setVisibility(View.GONE);
                    mTitleText.setVisibility(View.VISIBLE);

                    mTitleText.setText(R.string.information);
                    switchTask(TAG_MESSAGE);
                }
                hideTaskBt();
            } else if (v == mGroupBtLayout) {
                if (!TAB_CURR.equals(TAG_GROUP)) {
                    mTaskFunctionLayout.setVisibility(View.GONE);
                    mTitleText.setVisibility(View.VISIBLE);

                    mTitleText.setText(R.string.group);
                    switchTask(TAG_GROUP);
                }
                hideTaskBt();
            } else if (v == mMyBtLayout) {
                if (!TAB_CURR.equals(TAG_MY)) {
                    mTaskFunctionLayout.setVisibility(View.GONE);
                    mTitleText.setVisibility(View.VISIBLE);

                    mTitleText.setText(R.string.my);
                    switchTask(TAG_MY);
                }
                hideTaskBt();

//                EventBus.getDefault().post(new LogoutEvent("logout"));
            }
        }
    }

    // 显示title上PopWindow上的四个按钮
    private void showFourTaskBt() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.desk_card_four_bt_layout, null);
        // 设置按钮的点击事件
        mMyBtLayout = (LinearLayout) contentView.findViewById(R.id.my_bt_layout);
        mTaskBtLayout = (LinearLayout) contentView.findViewById(R.id.task_bt_layout);
        mMessageBtLayout = (LinearLayout) contentView.findViewById(R.id.message_bt_layout);
        mGroupBtLayout = (LinearLayout) contentView.findViewById(R.id.group_bt_layout);
        mMyLayout = (RelativeLayout)contentView.findViewById(R.id.my_layout);
        mMybt = (ImageView) contentView.findViewById(R.id.my_bt);
        mGroupbt = (ImageView) contentView.findViewById(R.id.group_bt);
        mMessagebt = (ImageView) contentView.findViewById(R.id.message_bt);
        mTaskbt = (ImageView) contentView.findViewById(R.id.task_bt);
        mTaskBtLayout.setOnClickListener(onButtonClick);
        mMessageBtLayout.setOnClickListener(onButtonClick);
        mGroupBtLayout.setOnClickListener(onButtonClick);
        mMyBtLayout.setOnClickListener(onButtonClick);

        selectOperButton();
        popupWindow = new PopupWindow(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(contentView);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(mContext,R.color.common_color_c10_eceff3));
        popupWindow.setWidth(getScreenParams().getWidth());
        popupWindow.showAtLocation(mMorebt, Gravity.TOP, 0, BaseApplication.getApplicationInstance().getStatusBarHeight());
    }

    // 隐藏四个tab的popwindow
    private void hideTaskBt() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    // 切换任务，在任务、消息、群组、我的中切换
    private void switchTask(String tag) {
        mMorebt.setVisibility(View.VISIBLE);

        // 切换Tab的时候，隐藏选择业务单位按钮
        hideFunctionUnitText();

        switchFragment(tag);

        if (TAB_CURR.equals(TAG_MESSAGE)) {
            EventBus.getDefault().post(new CardDeskMessageEvent("message"));
        }
        else if (TAB_CURR.equals(TAG_GROUP)) {
            EventBus.getDefault().post(new CardDeskMessageEvent("group"));
        }
    }

    // 切换任务，在任务、消息、群组、我的四个Fragment，这四个是根Fragment
    // 基于这四个Fragment往下走，用Fragment栈来切换
    Fragment mContent = null;

    private void switchFragment(String tag) {
        TAB_CURR = tag;
        cleanBackStack(); // 把任务栈里面的Fragment都清掉
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
        Fragment to = null;
        to = fm.findFragmentByTag(tag);
        if (to == null) {
            if (TAG_TASK.equals(tag)) {
                mDeskTaskFragment = new DeskTaskFragment();
                to = mDeskTaskFragment;
            } else if (TAG_MESSAGE.equals(tag)) {
                mDeskMessageFragment = new DeskMessageFragment();
                to = mDeskMessageFragment;
            } else if (TAG_GROUP.equals(tag)) {
                mDeskGroupFragment = new DeskGroupFragment();
                to = mDeskGroupFragment;
            } else if (TAG_MY.equals(tag)) {
                mDeskMyFragment = new DeskMyFragment();
                to = mDeskMyFragment;
            }
        }

        if (mContent != null) {
            if (mContent != to) {
                if (!to.isAdded()) {
                    ft.add(R.id.container, to, tag).hide(mContent);
                } else {
                    ft.show(to).hide(mContent);
                }
            }
        } else {
            if (!to.isAdded()) {
                ft.add(R.id.container, to, tag);
            } else {
                ft.show(to);
            }
        }
        mContent = to;
        ft.commitAllowingStateLoss();
    }

    // 选中title上popwindow四个按钮中的一个
    private void selectOperButton() {
        try {
            // 根据现在是哪个Tab来初始化选中状态
            if (TAG_TASK.equals(TAB_CURR)) {
                mTaskbt.setImageResource(R.drawable.nav_task_press);
                mMessagebt.setImageResource(R.drawable.message_bt_selector);
                mGroupbt.setImageResource(R.drawable.group_bt_selector);
                mMybt.setImageResource(R.drawable.my_bt_selector);
            } else if (TAG_MESSAGE.equals(TAB_CURR)) {
                mTaskbt.setImageResource(R.drawable.task_bt_selector);
                mMessagebt.setImageResource(R.drawable.nav_message_press);
                mGroupbt.setImageResource(R.drawable.group_bt_selector);
                mMybt.setImageResource(R.drawable.my_bt_selector);
            } else if (TAG_GROUP.equals(TAB_CURR)) {
                mTaskbt.setImageResource(R.drawable.task_bt_selector);
                mMessagebt.setImageResource(R.drawable.message_bt_selector);
                mGroupbt.setImageResource(R.drawable.nav_team_press);
                mMybt.setImageResource(R.drawable.my_bt_selector);
            } else if (TAG_MY.equals(TAB_CURR)) {
                mTaskbt.setImageResource(R.drawable.task_bt_selector);
                mMessagebt.setImageResource(R.drawable.message_bt_selector);
                mGroupbt.setImageResource(R.drawable.group_bt_selector);
                mMybt.setImageResource(R.drawable.nav_me_press);
            }
        } catch (Exception e) {

        }
    }

    public void onEventMainThread(CardDeskEvent event) {
        String msg = event.getMsg();
        if ("clear_back_stack".equals(msg)) {
            //清栈
            cleanBackStack();

            //刷新卡片桌面
            EventBus.getDefault().post(new CardDeskRefreshEvent(""));
            return;
        }

        //清栈，返回到卡片桌面，切换到相应的TAB
        cleanBackStack();

        if ("task".equals(msg)) {
            mTitleText.setText(R.string.task);
            switchTask(TAG_TASK);
        } else if ("info".equals(msg)) {
            mTitleText.setText(R.string.information);
            switchTask(TAG_MESSAGE);
        } else if ("group".equals(msg)) {
            mTitleText.setText(R.string.group);
            switchTask(TAG_GROUP);
        } else if ("my".equals(msg)) {
            mTitleText.setText(R.string.my);
            switchTask(TAG_MY);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeAllFragment();
    }

    // 从栈里面删除所有的fragment，清除数据用
    public void removeAllFragment() {
        try {
            cleanBackStack();

            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction trans = fm.beginTransaction();
            if (mDeskTaskFragment != null) {
                trans.remove(mDeskTaskFragment);
            }

            if (mDeskMessageFragment != null) {
                trans.remove(mDeskMessageFragment);
            }

            if (mDeskGroupFragment != null) {
                trans.remove(mDeskGroupFragment);
            }

            if (mDeskMyFragment != null) {
                trans.remove(mDeskMyFragment);
            }

            trans.commitAllowingStateLoss();
            if (mContainer != null) {
                mContainer.removeAllViews();
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onBackPressed() {
        // 判断如果popwindow显示就把它隐藏
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return;
        }
        super.onBackPressed();
    }

    private FingerprintIdentify mFingerprintIdentify;
    private boolean             mIsFingerStarted;

    @Override
    public void onResume() {

        if (BaseApplication.getApplicationInstance().isShowFingerPop()) {
            //登入状态
            String sp_token = sp.getValue(Constant.sp_Token);
            //指纹
            mFingerprintIdentify = new FingerprintIdentify(BaseApplication.getApplicationInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    LogUtils.showLog(exception.getLocalizedMessage());
                }
            });
            //是否开启指纹验证存
            mIsFingerStarted = BaseApplication.sp.getBooleanValue("sp_finger", false);
            if (!TextUtils.isEmpty(sp_token) && mIsFingerStarted && mFingerprintIdentify.isHardwareEnable()) {
                //跳activity
                ARouter.getInstance()
                        .build(Constant.PATH_FINGERLOGIN_ACTIVITY)
                        .withTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out)
                        .navigation(this);
                BaseApplication.getApplicationInstance().setShowFingerPop(false);
            }

        }
        super.onResume();
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        if (mContent != null) {
            if (mContent == mDeskTaskFragment) {
                savedInstanceState.putString("tab", "1");
            } else if (mContent == mDeskMessageFragment) {
                savedInstanceState.putString("tab", "2");
            } else if (mContent == mDeskGroupFragment) {
                savedInstanceState.putString("tab", "3");
            } else if (mContent == mDeskMyFragment) {
                savedInstanceState.putString("tab", "4");
            }
        }
    }

}
